<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80">
        <el-form-item class="!mr-0" label="完成时间" prop="timeScopes">
          <el-date-picker
            v-model="timeScopes"
            @change="validateYearRange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>
        <el-form-item label="单号" prop="code">
          <el-input
            v-noSpace
            v-model="queryParams.code"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleSeach"
            placeholder="请输入生产单号"
          >
            >
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            class="!w-[192px]"
            @change="handleSeach"
          >
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="productCode">
          <!-- <el-input v-noSpace v-model="queryParams.productName" placeholder="请输入产品名称">></el-input> -->
          <el-select
            v-model="queryParams.productCode"
            placeholder="请选择产品名称"
            clearable
            class="!w-[192px]"
            @change="handleSeach"
          >
            <el-option
              v-for="item in optionList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSeach">查询</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
          <el-button
            type="success"
            @click="downloadTable"
            class="!rounded-button whitespace-nowrap"
            v-hasPerm="'sys:productionOrder:exp'"
          >
            <el-icon class="mr-1"><Download /></el-icon>
            导出报表
          </el-button>
          <el-button
            @click="HistoryClick"
            type="info"
            class="!rounded-button whitespace-nowrap"
            v-hasPerm="'sys:productionOrder:down'"
          >
            <el-icon class="mr-1"><Document /></el-icon>
            历史报表下载
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        show-overflow-tooltip
        :tooltip-formatter="tableRowFormatter"
        :data="tableData"
      >
        <el-table-column prop="code" label="生产单号" min-width="160" align="left" />
        <el-table-column prop="statusStr" label="生产单状态" min-width="120"></el-table-column>
        <el-table-column prop="productName" label="生产产品" min-width="160" align="left" />
        <el-table-column prop="qty" label="预生产数量" min-width="120" align="right" />
        <el-table-column prop="entryQty" label="实际生产数量" min-width="120" align="right" />
        <el-table-column prop="unit" label="单位" min-width="80" align="center">
          <template #default="scope">
            {{ unitFormat(scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column prop="dosageQty" label="原材料消耗量" min-width="120" align="right" />
        <el-table-column prop="radio" label="出成率" min-width="100" align="right">
          <template #default="{ row }">
            <div v-if="row.radio">{{ row.radio }}%</div>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" min-width="160" align="center" />
        <el-table-column prop="finishTime" label="结束时间" min-width="160" align="center" />
        <el-table-column
          prop="pauseDuration"
          label="暂停时长(分钟)"
          min-width="140"
          align="right"
        />
        <el-table-column prop="workCount" label="排班工人数" min-width="120" align="right" />
        <!-- <el-table-column prop="workload" label="工作量" min-width="120" align="right" /> -->
      </el-table>
      <pagination
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleSeach"
      />
    </el-card>

    <!-- 历史报表下载弹窗 -->
    <el-dialog v-model="historyDialogVisible" title="历史报表下载" width="600px">
      <el-table :data="historyReports" style="width: 100%">
        <el-table-column prop="fileName" label="文件名称" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button @click="historyDownLoad(row.filePath, row.fileName)" type="primary" link>
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-model:total="peportTotal"
        v-model:page="reportParams.pageNum"
        v-model:limit="reportParams.pageSize"
        @pagination="reportHistoryList"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { tableRowFormatter } from "@/utils/index";
import { FormItemRule } from "element-plus/es";
import statementApi, { locationPageQuery } from "@/api/statement/statement";
import configApi, { ConfigType } from "@/api/config/config";

import { downLoad, historyDownLoad } from "@/utils/downLoad";
import { useDateRanges } from "@/utils/useDateRanges";
const historyDialogVisible = ref(false);
const reportType = 9;
const reportName = "生产报表";
const historyReports = ref([]);
const peportTotal = ref(0);
const reportParams: locationPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  reportType: reportType,
});
const reportHistoryList = () => {
  statementApi
    .getReportHistory(reportParams)
    .then((data) => {
      console.log(data);
      historyReports.value = [...(data.list as never)];
      historyReports.value.forEach((item: any) => {
        item.fileName = reportName + "_" + useDateRanges().getDate() + ".xlsx";
      });
      peportTotal.value = data.total;
    })
    .finally(() => {});
};
const HistoryClick = async () => {
  historyDialogVisible.value = true;
  reportHistoryList();
};
//下载表格
const downloadTable = () => {
  downLoad(queryParams, reportType, reportName);
};

// 类型
const optionList = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const getContractLists = () => {
  configApi
    .getProductList({ pageNum: 1, pageSize: 999, productType: "1" })
    .then((data) => {
      console.log(data, "data");
      // rowTableData.value = data?.list || [];
      optionList.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
      }));
    })
    .catch((error) => {
      //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
};

// 加载loading
const loading = ref(false);
// 分页总数
const total = ref(0);
// 搜索ref
const queryFormRef = ref(ElForm);
const timeScopes = ref([]);
const groupChange = () => {
  timeScopes.value = [];
};
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};
// 限制选择范围不超过365天
const validateYearRange = (val: any) => {
  if (!val || val.length !== 2) {
    return;
  }

  const [start, end] = val;
  const startDate = new Date(start);
  const endDate = new Date(end);

  // 计算两个日期之间的年份差
  const yearDiff = endDate.getFullYear() - startDate.getFullYear();
  const monthDiff = endDate.getMonth() - startDate.getMonth();
  const dayDiff = endDate.getDate() - startDate.getDate();

  // 如果年份差大于1年，或者正好1年但结束月份/日期大于开始月份/日期
  if (yearDiff > 1 || (yearDiff === 1 && (monthDiff > 0 || (monthDiff === 0 && dayDiff > 0)))) {
    ElMessage.error(`选择的时间范围不能超过一年`);

    timeScopes.value = [];
  }
};

const queryParams: locationPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  status: 6,
});
// 类型
const typeList = ref([
  { label: "计划已确认", value: 1 },
  { label: "备料中", value: 3 },
  { label: "待生产", value: 4 },
  { label: "生产中", value: 5 },
  { label: "已完成", value: 6 },
  { label: "已暂停", value: 7 },
]);

// 列表参数
const tableData = ref([]);

// 查询方法
const handleSeach = () => {
  loading.value = true;
  queryParams.startDate = timeScopes.value[0];
  queryParams.endDate = timeScopes.value[1];
  statementApi
    .getProductionReport(queryParams)
    .then((data) => {
      tableData.value = [...(data.list as never)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
// 重置方法
const handleReset = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  timeScopes.value = [];
  handleSeach();
};

onMounted(() => {
  handleSeach();
  getUnitList();
  getContractLists();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
